//
//  NetworkingManager+Extension.swift
//  weibo
//
//  Created by Fly on 2018/1/23.
//  Copyright © 2018年 Fly. All rights reserved.
//

import Foundation

// MARK: - 封装本APP的网络请求方法
extension NetworkManager {

    ///  加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博(比since_id时间晚的微博)，默认为0
    ///   - max_id: 返回ID比max_id小的微博(比max_id时间早的微博)，默认为0
    ///   - completion: 完成回调
    func statusList(since_id: Int64 = 0, max_id:Int64 = 0, completion:@escaping (_ list: [[String:Any]]?, _ isSuccess: Bool)->()) {
        
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params: [String : Any] = ["since_id": since_id, "max_id": max_id]
//        let params = ["since_id": "\(since_id)", "max_id": "\(max_id)"]
        
        tokenRequest(URLString: urlStr, parameters: params) { (json, isSuccess) in
            
            let dic = json as? [String: Any]
            
            let result = dic?["statuses"] as? [[String : Any]]
            
            completion(result , isSuccess)
            
        }
    }

    /// 返回微博的未读数量，定时刷新，不需要提示成功与失败
    ///
    /// - Returns: 返回微博的未读数量
    func unReadCount(completion: @escaping (_ count: Int) -> ()) {
        
//        guard let uid = uid else
        guard let uid = userAccount.uid else
        {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            
            let dic = json as? [String: Any]
            
            let count = dic?["status"] as? Int
            
            completion(count ?? 0)
            
        }
        
    }

}

// MARK: - 获取用户相关信息
extension NetworkManager {
    
    /// 加载用户信息 - 用户登录后立即执行
    func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject])->()) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        guard let uid = userAccount.uid else
        {
            return
        }
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlStr, parameters: params) { (json, isSuccess) in
            
            let dic = (json as? [String: AnyObject]) ?? [:]
            
            completion(dic)
            
        }
        
    }
    
}

// MARK: - OAuth授权
extension NetworkManager {
    
    func loadAccessToken(code: String, completion: @escaping (_ success: Bool)->()) {
       
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let parameter = [
                         "client_id": AppKey,
                         "client_secret": AppSecret,
                         "grant_type": "authorization_code",
                         "code": code,
                         "redirect_uri": RedirectURI
                         ]
        
        request(method: .POST, URLString: urlStr, parameters: parameter) { (json, isSuccess) in
            
            // 请求失败不会对上次请求的数据有影响
//            self.userAccount.yy_modelSet(with: (json as? [String: AnyObject]) ?? [:])
            self.userAccount.yy_modelSet(withJSON: (json as? [String: Any]) ?? [:])
            print("OAuth授权 self.userAccount -- \(self.userAccount)")

            // 保存模型
//            self.userAccount.saveAccount()

            //加载当前用户信息
            self.loadUserInfo(completion: { (dic) in
                
                // 使用用户信息字典设置用户账户信息-昵称，头像
                self.userAccount.yy_modelSet(withJSON: dic)
                
                // 保存模型
                self.userAccount.saveAccount()
                
                print("用户信息 - \(self.userAccount)")
                
                // 加载完用户信息再回调
                completion(isSuccess)
                
            })
            
        }
        
    }
    
}
